package edu.gdkm.ssm.dao;

import edu.gdkm.ssm.domain.UserInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 用户查询仓储
 */
public interface IUserDao {

    /**
     * 根据用户名查找用户信息
     * @param username 用户名
     * @return
     */
    @Select("select * from users where username=#{username}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id", javaType = java.util.List.class, many = @Many(select = "edu.gdkm.ssm.dao.IRoleDao.findRoleByUserId"))
    })
    UserInfo findByUserName(String username) throws Exception;

    /**
     * 查询所有用户信息
     * @return  所有用户信息
     */
    @Select("select * from users")
    List<UserInfo> findAll() throws Exception;


    /**
     * 新增用户信息
     * @param userInfo  用户信息
     */
    @Insert("insert into users(id, email, username, password, phoneNum, status) values " +
            "(replace(uuid(), '-', ''), #{email}, #{username}, #{password}, #{phoneNum}, #{status})")
    void save(UserInfo userInfo) throws Exception;

    /**
     * 根据用户id查询用户信息
     * @param id  用户id
     * @return  用户信息
     * @throws Exception
     */
    @Select("select * from users where id=#{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id", javaType = java.util.List.class, many = @Many(select = "edu.gdkm.ssm.dao.IRoleDao.findRoleByUserId"))
    })
    UserInfo findById(String id) throws Exception;

    /**
     * 给当前用户添加角色
     * @param userId 用户id
     * @param roleId 角色id
     */
    @Insert("insert into users_role(userId, roleId) value (#{userId}, #{roleId})")
    void addRoleToUser(@Param("userId") String userId, @Param("roleId") String roleId);
}
